﻿#include "MathManage.h"
#include "MathExpressBody.h"
#include <qhash.h>
#include "XmlDataDoc.h"
#include <QMutexLocker>
#include "MathPairUnit.h"

dXml::MathExpress::MathManage::MathManage(const QString& express) {
	this->express = express;
	bodyVector = new QVector<MathPairUnit*>;
	manageDel = new QHash<MathPairUnit*, bool>;
	isRun = false;
	mutex = new QMutex;
}

dXml::MathExpress::MathManage::~MathManage( ) {
	// 释放
	while( !bodyVector->isEmpty( ) ) {
		MathPairUnit* expressBody = bodyVector->last( );
		if( manageDel->contains(expressBody) ) {
			if( manageDel->value(expressBody) )
				delete expressBody;
			manageDel->remove(expressBody);
		}
		bodyVector->removeLast( );
	}
	QHash<MathPairUnit*, bool>::iterator iterator = manageDel->begin( );
	auto&& end = manageDel->end( );
	for( ;iterator != end;++iterator ) {
		if( iterator.value( ) )
			delete iterator.key( );
	}
	delete bodyVector;
	delete manageDel;
	delete mutex;
}

void dXml::MathExpress::MathManage::append(MathPairUnit* pair
	, bool manage) {
	bodyVector->append(pair);
	manageDel->insert(pair, manage);
	if( currPairUnit == Q_NULLPTR ) {
		currPairUnit = pair;
	//	pair->pResolve->start();
	}
}

void dXml::MathExpress::MathManage::remove(MathPairUnit* body
	, bool manage
	, bool force) {
	if( !bodyVector->removeOne(body) )
		return;
	if( manage )
		if( manageDel->contains(body) ) {
			if( manageDel->value(body) || force )
				delete body;
			manageDel->remove(body);
		}
}

void dXml::MathExpress::MathManage::clear(bool manage
	, bool force) {
	if( !manage && !force )
		bodyVector->clear( );
	auto iterator = bodyVector->begin( );
	auto end = bodyVector->end( );
	for( ;iterator != end;++iterator ) {
		if( manage ) {
			auto body = *iterator;
			if( manageDel->contains(body) ) {
				if( manageDel->value(body) || force )
					delete body;
				manageDel->remove(body);
			}
		}
	}
}

const quint32 dXml::MathExpress::MathManage::getSize( ) const {
	return bodyVector->size( );
}

dXml::XmlDataDoc dXml::MathExpress::MathManage::toDxmlDoc(bool clear) {
	return dXml::XmlDataDoc( );
}

const bool dXml::MathExpress::MathManage::isRunTask( ) const {
	QMutexLocker locker(mutex);
	return isRun;
}
